package com.time.workbench.core.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.time.workbench.auth.entity.base.ActiveUser;
import com.time.workbench.core.annotations.IgnoreAuth;
import com.time.workbench.core.consts.RedisKeyConst;
import com.time.workbench.core.consts.RequestAttributeKeyConst;
import com.time.workbench.core.consts.ResponseCode;
import com.time.workbench.core.util.AuthUtil;
import com.time.workbench.core.util.ContextUtil;
import org.slf4j.MDC;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.pattern.PathPattern;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求拦截器
 */
public class RequestInterceptor implements HandlerInterceptor {

    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("requestId", String.valueOf(System.currentTimeMillis()));
        MDC.put("requestUrl", request.getRequestURI());
        MDC.put("requestMethod", request.getMethod());

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getMethodAnnotation(IgnoreAuth.class) != null) {
                return true;
            }
            if (handlerMethod.getBeanType().getAnnotation(IgnoreAuth.class) != null) {
                return true;
            }

            // 获取请求头token
            String token = AuthUtil.getToken(request);
            if (StrUtil.isBlank(token)) {
                throw new AuthenticationException(ResponseCode.tokenNotFount.name());
            }
            if (redisTemplate == null)
                redisTemplate  = ContextUtil.getBean("stringObjectRedisTemplate");
            ActiveUser activeUser = (ActiveUser) redisTemplate.opsForValue().get(RedisKeyConst.AUTH + token);
            if (ObjectUtil.isNull(activeUser)) {
                throw new AuthenticationException(ResponseCode.tokenInvalidation.name());
            }
            request.setAttribute(RequestAttributeKeyConst.USERINFO, activeUser);
            request.setAttribute(RequestAttributeKeyConst.tenantId, 1);
            return true;
        }
        return true;
    }



}
